package com.kchouse.homepage;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.kchouse.MainActivity;
import com.kchouse.R;
import com.kchouse.common.API;
import com.kchouse.common.BaseActivity;
import com.kchouse.common.MyHttpCycleContext;
import com.kchouse.common.MyUtils;
import com.kchouse.common.ToastUtils;
import com.kchouse.mine.LoginPhoneActivity;
import com.kchouse.union.MerchantDetailsActivity;
import com.squareup.picasso.Picasso;

import java.io.File;
import java.net.URISyntaxException;

import cn.com.cesgroup.numpickerview.NumberPickerView;
import cn.finalteam.okhttpfinal.BaseHttpRequestCallback;
import cn.finalteam.okhttpfinal.HttpRequest;
import cn.finalteam.okhttpfinal.RequestParams;

public class PrestoreDetailsActivity extends BaseActivity implements View.OnClickListener {

    private PrestoreDetailsActivity mContent;
    private Intent intent;
    private String prestoreId;
    private TextView tv_title;
    private ImageView iv_back;
    private TextView tv_original;
    private TextView tv_goodtitle;
    private TextView tv_price;
    private ImageView iv_icon;
    private boolean isLogin = false;
    private View ll_nav;
    public static final String PACKEGE_GAODE = "com.autonavi.minimap";
    public static final String PACKEGE_BAIDU = "com.baidu.BaiduMap";
    private String merchantName;
    private String longitude;
    private String latitude;
    private String merchantId;
    private View ll_merchant;
    private Integer inventory;//库存
    private String prestorestr;
    private TextView tv_buy;
    private TextView tv_detail;
    private Integer cashNum;//现金券限制使用次数
    private View ll_collection;
    private ImageView iv_collection;
    private boolean iscollection = false;//是否收藏
    private String publishType;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_prestore_details);


        mContent = this;
        addAct(mContent);
        intiData();
        intiView();
    }

    private void intiView() {
        tv_title = (TextView) findViewById(R.id.tv_title);
        tv_title.setText("预存活动详情");
        iv_back = (ImageView) findViewById(R.id.iv_back);
        iv_back.setOnClickListener(this);

        tv_original = (TextView) findViewById(R.id.tv_original);
        tv_original.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);//添加下划线
        tv_goodtitle = (TextView) findViewById(R.id.tv_goodtitle);
        tv_price = (TextView) findViewById(R.id.tv_price);
        tv_detail = (TextView) findViewById(R.id.tv_detail);
        iv_icon = (ImageView) findViewById(R.id.iv_icon);


        ll_nav = findViewById(R.id.ll_nav);
        ll_nav.setOnClickListener(this);
        ll_merchant = findViewById(R.id.ll_merchant);
        ll_merchant.setOnClickListener(this);
        tv_buy = (TextView) findViewById(R.id.tv_buy);
        tv_buy.setOnClickListener(this);

        ll_collection =findViewById(R.id.ll_collection);
        ll_collection.setOnClickListener(this);
        iv_collection = (ImageView) findViewById(R.id.iv_collection);
    }


    private void intiData() {
        intent = getIntent();
        prestoreId = intent.getStringExtra("prestoreId");
        GetPrestoreDetails(prestoreId);

    }

    /**
     * 获取预存活动详情
     * @param id
     */
    private void GetPrestoreDetails(String id) {
        String url = API.GetPrestoreDetails + id;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数

        params.addFormDataPart("prestoreId", id);

        HttpRequest.get(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    prestorestr = data.getString("prestore");
                    JSONObject prestorejson = JSONObject.parseObject(prestorestr);
                    tv_goodtitle.setText(prestorejson.getString("title"));
                    if(prestorejson.getDouble("originalPrice")!=0){
                        tv_original.setText(prestorejson.getDouble("originalPrice")+"");
                    }
                    tv_price.setText(MyUtils.getdouble2(prestorejson.getDouble("price")));
                    Picasso.with(mContent).load(prestorejson.getString("url")).error(R.mipmap.ic_loadingerror).into(iv_icon);

                    merchantName=  prestorejson.getString("merchantName");
                    longitude=  prestorejson.getString("longitude");
                    latitude=  prestorejson.getString("latitude");
                    merchantId=  prestorejson.getString("merchantId");
                    tv_detail.setText(prestorejson.getString("detail"));
                    inventory=  prestorejson.getInteger("inventory");
                    cashNum=  prestorejson.getInteger("cashNum");
                    publishType=  prestorejson.getString("type");
                } else {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    ToastUtils.getInstanc(mContent).showToast(data.getString("msg"));
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
                dismissdialog();
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                delAct(mContent);
                finish();
                break;
            case R.id.ll_nav:
                navigation("厦门", merchantName,latitude , longitude);
                break;
            case R.id.ll_merchant:
                if (checkLogin()) return;
                intent.putExtra("Merchantid", merchantId);
                intent.setClass(mContent, MerchantDetailsActivity.class);
                startActivity(intent);
                break;
            case R.id.tv_buy:
                if (checkLogin()) return;
                shownpv();
                break;
            case R.id.ll_collection:
                if (checkLogin()) return;
                if (iscollection) {
                    DelCollection();
                } else {
                    PostAddCollection();
                }
                break;
        }
    }


    /**
     * 添加收藏
     */
    private void PostAddCollection() {
        String url = API.PostAddCollection;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数
        params.addHeader("token", MainActivity.token);//添加header信息
        JSONObject ob = new JSONObject();
        ob.put("userId", MainActivity.userid);
        ob.put("suitId", prestoreId);
        ob.put("type", publishType);
        params.applicationJson(ob);


        HttpRequest.post(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
                    String datastr = json.getString("data");
                    iv_collection.setImageResource(R.mipmap.ic_collection_on);
                    iscollection = true;
                } else {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    ToastUtils.getInstanc(mContent).showToast(data.getString("msg"));
                    if (data.getString("code").equals("401")) {
                        intent.setClass(mContent, LoginPhoneActivity.class);
                        startActivity(intent);
                    }
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
                dismissdialog();
            }
        });
    }

    /**
     * 移除收藏
     */
    private void DelCollection() {
        String url = API.DelCollection+ "/"+MainActivity.userid + "/" + prestoreId;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数
        params.addHeader("token", MainActivity.token);//添加header信息
        params.addFormDataPart("userId", MainActivity.userid);
        params.addFormDataPart("suitId", prestoreId);
        HttpRequest.delete(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
                    String datastr = json.getString("data");
                    iv_collection.setImageResource(R.mipmap.ic_collection_off);
                    iscollection = false;
                } else {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    ToastUtils.getInstanc(mContent).showToast(data.getString("msg"));
                    if (data.getString("code").equals("401")) {
                        intent.setClass(mContent, LoginPhoneActivity.class);
                        startActivity(intent);
                    }
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
                dismissdialog();
            }
        });
    }


    /**
     * 显示数量购买选择器
     */
    private void shownpv() {
        // 创建构建器
        AlertDialog.Builder builder = new AlertDialog.Builder(mContent);
//        builder.setView(getResources().getLayout(R.layout.lay_umberpickerview));
        View view = getLayoutInflater().inflate(R.layout.lay_umberpickerview, null);
        final NumberPickerView npv_item = (NumberPickerView) view.findViewById(R.id.npv_item);
        npv_item.setMaxValue(100) //最大输入值，也就是限量，默认无限大
                .setCurrentInventory(inventory) // 当前的库存
                .setMinDefaultNum(1)  // 最小限定量
                .setCurrentNum(1)  // 当前数量
                .setmOnClickInputListener(new NumberPickerView.OnClickInputListener() {
                    @Override
                    public void onWarningForInventory(int inventory) {
                        ToastUtils.getInstanc(mContent).showToast("超过最大库存");
                    }

                    @Override
                    public void onWarningMinInput(int minValue) {
//                        ToastUtils.getInstanc(mContent).showToast("低于最小设定值");
                    }

                    @Override
                    public void onWarningMaxInput(int maxValue) {
                        ToastUtils.getInstanc(mContent).showToast("超过最大限制量");
                    }
                });
        builder.setView(view);


        // 设置参数
        builder.setTitle("请选择购买数量").
                setPositiveButton("确定", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog,
                                        int which) {
//                ToastUtils.getInstanc(mContent).showToast(npv_item.getNumText()+"");


                        intent.putExtra("buynum", npv_item.getNumText());
                        intent.putExtra("cashNum", cashNum);
                        intent.putExtra("prestorestr", prestorestr);
                        intent.setClass(mContent, BuyPrestoreOrderActivity.class);
                        startActivity(intent);


                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        builder.create().show();
    }




    /**
     * 城市名 位置名  目的地纬度 目的地经度(跳转到地图软件进行导航,优先选用高德地图,其次用百度地图)
     */
    private void navigation(String city, String position, String lat, String lon) {
        try {
            Intent intent = null;
            if (isInstallByread(PACKEGE_GAODE)) {
                //高德地图导航的代码
//                Toast.makeText(context, "打开高德地图", Toast.LENGTH_SHORT).show();
                intent = Intent.parseUri("androidamap://viewMap?sourceApplication=appname&poiname=" + position + "&lat=" + lat + "&lon=" + lon + "&dev=0", 0);
            } else if (isInstallByread(PACKEGE_BAIDU)) {
                //百度地图导航的代码
//                Toast.makeText(context, "打开百度地图", Toast.LENGTH_SHORT).show();
                intent = Intent.parseUri("intent://map/geocoder?location=" + lat + "," + lon + "&coord_type=gcj02&src=yourCompanyName|yourAppName#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end", 0);
            } else {
//                ToastUtils.getInstanc(context).showToast("未安装高德或者百度地图软件");
            }
            if (intent != null) {
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }

    /**
     * 校验登录状态
     *
     * @return
     */
    private boolean checkLogin() {
        // 如果未登录都进入登录界面
        if (!isLogin) {
            intent.setClass(mContent, LoginPhoneActivity.class);
            startActivity(intent);
            return true;
        }
        return false;
    }

    /**
     * 判断是否安装目标应用
     *
     * @param packageName 目标应用安装后的包名
     * @return 是否已安装目标应用
     */
    private boolean isInstallByread(String packageName) {
        return new File("/data/data/" + packageName).exists();
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (!MainActivity.mobile.equals("")) {
            isLogin = true;
            GetCheckCollection();
        } else {
            isLogin = false;
        }
    }


    /**
     * 检测是否已经收藏
     */
    private void GetCheckCollection() {
        String url = API.GetCheckCollection + MainActivity.userid + "/" + prestoreId;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数
        params.addFormDataPart("userId", MainActivity.userid);
        params.addFormDataPart("suitid",prestoreId);
        params.addHeader("token", MainActivity.token);//添加header信息

        HttpRequest.get(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
                    iscollection = json.getBooleanValue("data");
                    if (iscollection) {
                        iv_collection.setImageResource(R.mipmap.ic_collection_on);
                    } else {
                        iv_collection.setImageResource(R.mipmap.ic_collection_off);
                    }

                } else {
                    String datastr = json.getString("data");
//                    JSONObject data = JSONObject.parseObject(datastr);
//                    ToastUtils.getInstanc(getActivity()).showToast(data.getString("msg"));
//                    if (data.getString("code").equals("401")) {
//                        intent.setClass(getActivity(), LoginPhoneActivity.class);
//                        startActivity(intent);
//                    }
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
                dismissdialog();
            }
        });
    }



    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            delAct(mContent);
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


}
